﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace Medianamik.UI.Web.UserControls
{
	public partial class SearchBox : BaseUserControl
	{
        public string SearchText
        {
            get { return txtSearch.Text; }
            set { txtSearch.Text = value; }
        }

        public Guid SelectedModule
        {
            get { return new Guid(ddlModules.SelectedValue); }
            set { ddlModules.SelectedValue = value.ToString(); }
        }

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				ddlModules.DataBind();
                var currentModule = Page.CurrentModule;
                if (currentModule != null)
                {
                    var searchResultPageId = currentModule.SearchResultPageId;
                    if (searchResultPageId.HasValue)
                        ddlModules.SelectedValue = searchResultPageId.ToString();
                }
			}
		}

		protected void btnSubmit_Click(object sender, EventArgs e)
		{
			var node = SiteMap.Provider.FindSiteMapNodeFromKey(ddlModules.SelectedValue);
			if(node!= null)
			{
				string qs = "?q=" + HttpUtility.UrlEncode(txtSearch.Text);
				Response.Redirect(node.Url  + qs);
			}
		}

	    protected IEnumerable<KeyValuePair<string, string>> GetModules()
		{
			// Sélection des modules qui ont une page de recherche
			// et dont cette page de recherche est accessible
			// à l'utilisateur
			return (from page in SiteMap.RootNode.GetAllNodes().Cast<SiteMapNode>()
                   let id = page["searchPageId"]
				   let searchPage = string.IsNullOrEmpty(id)
				   ? null
                   : SiteMap.Provider.FindSiteMapNodeFromKey(id)
                   where searchPage != null
                       && searchPage.IsAccessibleToUser(Context)
                   select new KeyValuePair<string,string>(searchPage.Key, page["moduleTitle"]))
                   .Distinct();
			
		}

		
	}
}